/*Cpr billhainh*/

#include "VS2DwordRecorder.h"

QFile wordDataBase (":/wordDb");
QTextStream wordDataStream (&wordDataBase );

wordRecorder::wordRecorder(QWidget *parent) :
    QMainWindow(parent),
    wRecUi(new Ui::wordRecorder),
    outputLocationSet(false)
{
    wRecUi->setupUi(this);

    audiosource = new QAudioCaptureSource(this);
    capture = new QMediaRecorder(audiosource, this);
    player = new QMediaPlayer;

    wordDataBase.open(QIODevice::ReadOnly);
    wRecUi->wordLeft->display( wordLeft = 8769);

    if(!QFile("saveSession").exists())
        wRecUi->continueButton->setEnabled(false);

    //audio devices
  wRecUi->audioDeviceBox->addItem(tr("Default"), QVariant(QString()));
    foreach(const QString &device, audiosource->audioInputs()) {
        wRecUi->audioDeviceBox->addItem(device, QVariant(device));
   }

    //audio codecs
    wRecUi->audioCodecBox->addItem(tr("Default"), QVariant(QString()));
    foreach(const QString &codecName, capture->supportedAudioCodecs()) {
        wRecUi->audioCodecBox->addItem(codecName, QVariant(codecName));
    }

     QTextCursor cursor = wRecUi->wordChart->textCursor();
     cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::MoveAnchor, 1);

    wRecUi->qualitySlider->setRange(0, int(QtMultimediaKit::VeryHighQuality));
    wRecUi->qualitySlider->setValue(int(QtMultimediaKit::VeryHighQuality));

    //bitrates:
    wRecUi->bitrateBox->addItem(QString("Default"), QVariant(0));
    wRecUi->bitrateBox->addItem(QString("32000"), QVariant(32000));
    wRecUi->bitrateBox->addItem(QString("64000"), QVariant(64000));
    wRecUi->bitrateBox->addItem(QString("96000"), QVariant(96000));
    wRecUi->bitrateBox->addItem(QString("128000"), QVariant(128000));

    connect(capture, SIGNAL(durationChanged(qint64)), this,
            SLOT(updateProgress(qint64)));
    connect(capture, SIGNAL(stateChanged(QMediaRecorder::State)), this,
            SLOT(updateState(QMediaRecorder::State)));
    connect(capture, SIGNAL(error(QMediaRecorder::Error)), this,
            SLOT(displayErrorMessage()));
    }

wordRecorder::~wordRecorder()
{
    saveSession();
    delete capture;
    delete audiosource;
}

void wordRecorder::saveSession()
{
    QFile saveSession ("saveSession");
    saveSession.open(QIODevice::WriteOnly);
    QTextStream lastW (&saveSession);
    lastW<<wordName<<"\n"<<wordLeft<<"\n";
}

void wordRecorder::restoreSession()
{
           QFile restoreSession ("saveSession");
           restoreSession.open(QIODevice::ReadOnly);
           QTextStream restoreSes(&restoreSession);
           lastSes = restoreSes.readLine();
           while(wordName != lastSes) {
                        wordName = wordDataStream.readLine();
           }
           wRecUi->wordChart->setPlainText(wordName);
           wordLeft =restoreSes.readLine().toDouble();
           wRecUi->wordLeft->display(wordLeft);
}

void wordRecorder::updateProgress(qint64 duration)
{
    if (capture->error() != QMediaRecorder::NoError || duration < 2000)
        return;

    wRecUi->statusbar->showMessage(tr("Recorded %1 sec").arg(qRound(duration / 1000)));
}

void wordRecorder::updateState(QMediaRecorder::State state)
{
    QString statusMessage;

    switch (state) {
        case QMediaRecorder::RecordingState:
            wRecUi->recordButton->setText(tr("Stop"));
            if (capture->outputLocation().isEmpty())
                statusMessage = tr("Recording");
            else
                statusMessage = tr("Recording to %1").arg(
                        capture->outputLocation().toString());
            break;
    case QMediaRecorder::PausedState:
            break;
        case QMediaRecorder::StoppedState:
            wRecUi->recordButton->setText(tr("Record"));
            statusMessage = tr("Stopped");
    }

    wRecUi->nextWord->setEnabled(state!=QMediaRecorder::RecordingState);

    wRecUi->listenButton->setEnabled(state!=QMediaRecorder::RecordingState);

    if (capture->error() == QMediaRecorder::NoError)
        wRecUi->statusbar->showMessage(statusMessage);
}

static QVariant boxValue(const QComboBox *box)
{
    int idx = box->currentIndex();
    if (idx == -1)
        return QVariant();

    return box->itemData(idx);
}

void wordRecorder::displayErrorMessage()
{
    wRecUi->statusbar->showMessage(capture->errorString());
}

QUrl wordRecorder::generateAudioFilePath()
{
    if(!QDir("Voice").exists())
        QDir().mkdir("Voice");
   if (QuickModeOff==false)
        wRecUi->wordChart->setPlainText(wordName);
    QString wName = wordName;
     QUrl location(QDir().toNativeSeparators (
                      QDir().currentPath() +
                      QString("/Voice/") +
                      wName +
                     QString(".ogg")
        ));
   if (QuickModeOff==false){
           wordName = wordDataStream.readLine();
           wRecUi->wordLeft->display(--wordLeft);
   }
   wordPlace = location;
    return location;
}

//Action Fn:

void wordRecorder::toggleRecord()
{
    if (capture->state() == QMediaRecorder::StoppedState) {
        audiosource->setAudioInput(boxValue(wRecUi->audioDeviceBox).toString());

        if (!outputLocationSet)
            capture->setOutputLocation(generateAudioFilePath());

        QAudioEncoderSettings settings;
        settings.setCodec(boxValue(wRecUi->audioCodecBox).toString());
        settings.setBitRate(boxValue(wRecUi->bitrateBox).toInt());
        settings.setQuality(QtMultimediaKit::EncodingQuality(wRecUi->qualitySlider->value()));
        settings.setEncodingMode(wRecUi->constantQualityRadioButton->isChecked() ?
                                 QtMultimediaKit::ConstantQualityEncoding :
                                 QtMultimediaKit::ConstantBitRateEncoding);

        QString container = "ogg";

        capture->setEncodingSettings(settings, QVideoEncoderSettings(), container);
        capture->record();
        while (capture->duration () ==  7)
            capture->stop ();
    }
    else {
        capture->stop();
    }
}

void wordRecorder::on_nextWord_clicked()
{
    wordName = wordDataStream.readLine();
    wRecUi->wordChart->setPlainText(wordName);
    wRecUi->wordLeft->display(--wordLeft);
}

void wordRecorder::on_continueButton_clicked()
{
    restoreSession();
    wRecUi->continueButton->setEnabled(false);
}

void wordRecorder::on_quickModeButton_clicked(bool checked)
{
   (QuickModeOff==false) ?
              ( (QuickModeOff=true)&&( checked=true))
                : ((QuickModeOff=false)&&(checked = false)) ;
}

//Unstable Fn:

void wordRecorder::on_listenButton_clicked()
{
    if (player->state() ==QMediaPlayer::StoppedState)
     {
         wordPlaceS = generateAudioFilePath ().toString ();
          player->setMedia (QUrl().fromLocalFile (wordPlaceS));
          player->setVolume(50);
          player->play();
          wRecUi->listenButton->setText ("Stop");
     }
      else
    {
        player->stop();
        wRecUi->listenButton->setText ("Listen");
    }
}

//1314.TM//
